package linkedList.递归;

import po.ListNode;

/**
 * @author songZiHao
 * @version 1.0.0
 * @ClassName 翻转前N个节点的链表.java
 * @Description TODO https://labuladong.gitbook.io/algo/shu-ju-jie-gou-xi-lie/shou-ba-shou-shua-lian-biao-ti-mu-xun-lian-di-gui-si-wei/di-gui-fan-zhuan-lian-biao-de-yi-bu-fen#er-fan-zhuan-lian-biao-qian-n-ge-jie-dian
 * @createTime 2021年03月08日 15:28:00
 */
public class 翻转前N个节点的链表 {

	/**
	 * 因为是前N个节点的翻转，所以头结点在翻转后并不一定是链表的最后一个节点，所以需要知道，翻转之前的最后的一个节点的下一个节点是什么节点，
	 * 然后在翻转之后，把翻转之后的尾结点指向记录的临时节点
	 */
	ListNode temp = null;

	public static void main(String[] args) {
		ListNode listNode1 = new ListNode(1);
		ListNode listNode2 = new ListNode(2);
		ListNode listNode3 = new ListNode(3);
		ListNode listNode4 = new ListNode(4);
		ListNode listNode5 = new ListNode(5);
		listNode1.next = listNode2;
		listNode2.next = listNode3;
		listNode3.next = listNode4;
		listNode4.next = listNode5;
		翻转前N个节点的链表 list = new 翻转前N个节点的链表();
		ListNode node = list.reverseList(listNode1, 2);
		System.out.println(node);
	}
	public ListNode reverseList(ListNode head, int length) {
		if (length == 1) {
			temp = head.next;
			return head;
		}
		ListNode lastNode = reverseList(head.next, length - 1);
		head.next.next=head;
		head.next=temp;
		return lastNode;
	}
}
